<template>
  <div>
    <div class="header">
      <span>新闻发布</span>
      <span class="preview-link" @click="handlePreview">预览</span>
    </div>
    <Nodata v-if="!loading && !releaseList.length"></Nodata>

    <div class="container" v-else>
      <el-card class="release-card">
        <!-- 步骤指示器 -->
        <div class="steps-indicator mb-8">
          <div class="step-item" :class="{ active: currentStep === 1 }">
            <div class="step-number">{{ 1 }}</div>
            <div class="step-title">发布内容</div>
          </div>
          <div class="step-line" :class="{ active: currentStep >= 2 }"></div>
          <div class="step-item" :class="{ active: currentStep === 2 }">
            <div class="step-number">{{ 2 }}</div>
            <div class="step-title">发布设置</div>
          </div>
        </div>

        <!-- 步骤1：发布内容 -->
        <div v-if="currentStep === 1" class="step-content">
          <div v-if="loading" class="text-center py-4">
            <el-icon class="is-loading"><Loading /></el-icon>
            <p>加载中...</p>
          </div>

          <div>
            <template v-for="type in newsTypes" :key="type.id">
              <div v-if="getCategoryList(type.id).length" class="news-category">
                {{ `${type.name} (${getCategoryList(type.id).length})` }}
              </div>

              <div class="news-list" v-if="getCategoryList(type.id).length">
                <div v-for="(item, index) in getCategoryList(type.id)" :key="item.id" class="news-item">
                  <div class="news-header">
                    <span class="news-tag">{{ type.name }}</span>
                    <h3 class="news-title">{{ item.newsTitle }}</h3>
                    <div class="news-order">
                      <div class="flex flex-row">
                        <img :src="Arrow" alt="" :style="{ opacity: index === 0 ? 0.2 : 1 }" class="svg-icon"
                          @click="handleMove('up', item)"></img>
                        <img :src="Arrow" alt=""
                          :style="{ opacity: index === getCategoryList(type.id).length - 1 ? 0.2 : 1 }"
                          class="svg-icon rotate-180" @click="handleMove('down', item)" />
                      </div>
                    </div>
                  </div>

                  <div class="news-abstract">{{ item.abstractReal }}</div>

                  <div class="news-meta">
                    <span class="news-source">{{ item.siteName || item.newsSource }}</span>
                    <span class="news-time">{{ formatDate(item.createTime) }}</span>
                    <span class="news-author">由{{ item.opPerson }}添加</span>
                    <div class="news-actions" v-if="permissionMode === 'write'">
                      <button class="action-btn edit-btn" @click="handleEdit(item)">
                        <el-icon class="icon"><EditPen /></el-icon>编辑
                      </button>
                      <button class="action-btn remove-btn" @click="removeData(item.id)">
                        <el-icon class="icon"><Minus /></el-icon>移除
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </div>

          <div class="text-center mt-8">
            <el-button v-if="releaseList.length" type="primary" size="default" @click="currentStep = 2"
              class="next-btn">下一步</el-button>
          </div>
        </div>

        <!-- 步骤2：发布设置 -->
        <div v-if="currentStep === 2" class="step-content">
          <NewsPublishNext ref="newsPublishNextRef" :current-step="currentStep" @update:currentStep="val => currentStep = val" />
        </div>
      </el-card>
    </div>
    <Editor v-model="showEditor" :data="currentEditItem" @save="handleSaveEdit" />
  </div>
</template>

<script>
import { ref, onMounted, reactive, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { Loading, EditPen, Minus } from '@element-plus/icons-vue';
import { useRouter, useRoute } from 'vue-router'; // 新增useRoute引入
import { format } from 'date-fns';
import Editor from '@/Components/Editor.vue';
import { getReleaseList, insertPublish, updateNews, orderNews } from '@/Api/newsApi';
import Arrow from '@/assets/circle-arrow.svg'
import Nodata from './Nodata.vue';
import NewsPublishNext from '@/Components/NewsPublishNext.vue';

export default {
  components: {
    Editor,
    Loading,
    EditPen,
    Minus,
    Nodata,
    NewsPublishNext,
  },
  setup() {
    const list = ref([]);
    const loading = ref(true);
    const showEditor = ref(false);
    const router = useRouter();
    const route = useRoute(); // 新增：获取当前路由实例
    const releaseList = ref([]);
    // 新增：优先从路由参数取步骤，无参数时默认1
    const currentStep = ref(route.query.step ? Number(route.query.step) : 1);
    const currentEditItem = ref(null);
    const coverFileList = ref([]);
    const permissionMode = ref('write');
    const newsPublishNextRef = ref(null); // 用于引用NewsPublishNext组件

    const newsTypes = [
      { id: 1, name: '宏观形势' },
      { id: 2, name: '行业动态' },
      { id: 3, name: '产业链动态' },
      { id: 4, name: '国际能源观察' },
      { id: 5, name: '其他' }
    ];

    const publishForm = reactive({
      title: '',
      summary: '',
      coverImage: '',
      timeType: 'immediate',
      scheduleTime: null
    });

    // 关键修改：跳转预览页时携带currentStep参数和表单数据
    const handlePreview = async () => {
      if (!releaseList.value.length) {
        ElMessage.warning('暂无内容可预览');
        return;
      }
      
      // 获取表单数据（如果当前在步骤2）
      let formData = null;
      if (currentStep.value === 2) {
        // 确保组件已挂载
        await nextTick();
        
        // 尝试从子组件获取表单数据
        if (newsPublishNextRef.value) {
          formData = newsPublishNextRef.value.getFormData();
        } else {
          // 如果组件引用不可用，尝试从临时存储获取数据
          try {
            const tempData = sessionStorage.getItem('tempFormData');
            if (tempData) {
              formData = JSON.parse(tempData);
            }
          } catch (error) {
            console.error('从临时存储获取表单数据失败', error);
          }
        }
      }
      
      // 存储数据到sessionStorage
      sessionStorage.setItem('previewNewsList', JSON.stringify(releaseList.value));
      if (formData) {
        sessionStorage.setItem('previewFormData', JSON.stringify(formData));
      }
      
      // 路由跳转时添加query参数step，值为当前步骤
      router.push({ name: 'preview', query: { step: currentStep.value } });
    };

    const getCategoryList = (typeId) => {
      return releaseList.value.filter(item => item.classReal === typeId);
    };

    const formatDate = (dateString) => {
      if (!dateString) return '';
      return format(new Date(dateString), 'yyyy-MM-dd HH:mm:ss');
    };

    const handleMove = (direction, item) => {
      if (!item || !item.id) {
        console.error('无效的新闻项');
        return;
      }
      const categoryList = getCategoryList(item.classReal);
      const currentCategoryIndex = categoryList.findIndex(newsItem => newsItem.id === item.id);
      const currentIndex = releaseList.value.findIndex(newsItem => newsItem.id === item.id);

      if (currentIndex === -1) {
        console.error('未找到新闻项');
        return;
      }
      if (direction === 'up') {
        if (currentCategoryIndex === 0) return;
        const prevItem = categoryList[currentCategoryIndex - 1];
        const prevIndex = releaseList.value.findIndex(newsItem => newsItem.id === prevItem.id);
        [releaseList.value[currentIndex], releaseList.value[prevIndex]] = [releaseList.value[prevIndex], releaseList.value[currentIndex]];
      } else if (direction === 'down') {
        if (currentCategoryIndex === categoryList.length - 1) return;
        const nextItem = categoryList[currentCategoryIndex + 1];
        const nextIndex = releaseList.value.findIndex(newsItem => newsItem.id === nextItem.id);
        [releaseList.value[currentIndex], releaseList.value[nextIndex]] = [releaseList.value[nextIndex], releaseList.value[currentIndex]];
      }
    }

    const handleCoverUpload = (response) => {
      if (response.code === 200) {
        publishForm.coverImage = response.data.url;
        coverFileList.value = [{
          name: response.data.filename,
          url: response.data.url,
          uid: response.data.id
        }];
        ElMessage.success('封面上传成功');
      } else {
        ElMessage.error('封面上传失败');
      }
    };

    const fetchReleaseList = async () => {
      try {
        loading.value = true;
        const result = await getReleaseList();
        releaseList.value = result.list || [];
      } catch (error) {
        console.error('获取待发布列表失败', error);
        ElMessage.error('获取待发布列表失败');
      } finally {
        loading.value = false;
      }
    };

    const removeData = async (id) => {
      try {
        await updateNews({ id, isSelect: 0 });
        releaseList.value = releaseList.value.filter(item => item.id !== id);
        ElMessage.success('移除成功');
      } catch (error) {
        console.error('移除失败', error);
        ElMessage.error('移除失败');
      }
    };

    const handleEdit = (item) => {
      currentEditItem.value = JSON.parse(JSON.stringify(item));
      showEditor.value = true;
    };

    const handleSaveEdit = (editedItem) => {
      const index = releaseList.value.findIndex(item => item.id === editedItem.id);
      if (index !== -1) releaseList.value[index] = editedItem;
      showEditor.value = false;
      
      ElMessage.success('编辑成功');
    };

    const publishNews = async () => {
  try {
    if (!publishForm.title) return ElMessage.warning('请输入发布标题');
    if (!publishForm.summary) return ElMessage.warning('请输入发布摘要');
    if (publishForm.timeType === 'scheduled' && !publishForm.scheduleTime) {
      return ElMessage.warning('请选择定时发布时间');
    }

    // 调用发布接口
    const publishResult = await insertPublish({
      newsIds: releaseList.value.map(item => item.id),
      title: publishForm.title,
      summary: publishForm.summary,
      coverImage: publishForm.coverImage,
      timeType: publishForm.timeType,
      scheduleTime: publishForm.scheduleTime ? new Date(publishForm.scheduleTime).toISOString() : null
    });

    // 调用 publishReleaseList 接口记录发布信息
    await publishReleaseList({
      issueNo: publishResult.issueNo, // 假设发布接口返回了issueNo
      current: 1,
      currentSize: 10
    });

    // 更新新闻状态
    for (const item of releaseList.value) {
      await updateNews({ id: item.id, isPublished: 1, isSelect: 0 });
    }

    ElMessage.success('发布成功');
    router.push('/published'); // 跳转到已发布新闻页面
  } catch (error) {
    console.error('发布失败', error);
    ElMessage.error('发布失败');
  }
};

    onMounted(fetchReleaseList);

    return {
      loading,
      releaseList,
      publishForm,
      coverFileList,
      Arrow,
      showEditor,
      currentEditItem,
      newsTypes,
      currentStep,
      getCategoryList,
      formatDate,
      handleMove,
      handleCoverUpload,
      removeData,
      handleEdit,
      handleSaveEdit,
      publishNews,
      permissionMode,
      handlePreview
    };
  }
};
</script>

<style>
.arrow-icon { margin-left: 10px; }
.centered-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 30px;
  padding: 0;
}
.centered-buttons .el-button { min-width: 100px; }
.svg-icon {
  width: 24px;
  height: 24px;
  vertical-align: middle;
  margin-right: 10px;
}
.header {
  padding: 12px 20px;
  font-size: 18px;
  background-color: #ffffff;
  border-bottom: 1px solid #ebeef5;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.preview-link {
  color: #1890ff;
  cursor: pointer;
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}
.preview-link:hover { background-color: #f0f7ff; }
.container {
  width: 90%;
  max-width: 1200px;
  margin: 20px auto;
  background-color: #ffffff;
}
.release-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border-radius: 4px;
  border: none;
}
.steps-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  gap: 10px;
  margin: 20px 0 30px;
  padding: 0 20px;
}
.step-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: auto;
  margin: 0 15px;
}
.step-number {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #e5e7eb;
  color: #6b7280;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 16px;
}
.step-title {
  color: #6b7280;
  font-size: 14px;
  text-align: center;
  margin-top: 5px;
}
.step-line {
  flex: 1;
  height: 2px;
  background-color: #e5e7eb;
  max-width: 120px;
}
.step-item.active .step-number { background-color: #1890ff; color: white; }
.step-item.active .step-title { color: #1890ff; font-weight: 500; }
.step-line.active { background-color: #1890ff; }
.step-content {
  width: 85%;
  margin: 0 auto;
  padding-bottom: 30px;
}
.news-category {
  font-size: 16px;
  color: #333;
  margin: 25px 0 15px;
  font-weight: 500;
}
.news-list { margin-bottom: 20px; }
.news-item {
  padding: 18px 0;
  border-bottom: 1px solid #f0f0f0;
}
.news-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
  gap: 12px;
}
.news-tag {
  padding: 3px 8px;
  background-color: #f0f9eb;
  color: #52c41a;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  margin-top: 2px;
}
.news-title {
  flex: 1;
  font-size: 16px;
  color: #1890ff;
  font-weight: 600;
  margin: 0;
  line-height: 1.4;
}
.news-order {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-left: 10px;
}
.icon {
  width: 16px;
  height: 16px;
  color: #666;
}
.news-abstract {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
  margin-bottom: 12px;
  padding-right: 40px;
}
.news-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  font-size: 12px;
  color: #666;
  gap: 20px;
}
.news-author { margin-right: auto; }
.news-actions {
  display: flex;
  gap: 15px;
  margin-left: 10px;
}
.action-btn {
  background: none;
  border: none;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  font-size: 12px;
  padding: 0;
  gap: 4px;
}
.edit-btn { color: #1890ff; }
.remove-btn { color: #ff4d4f; }
.remove-btn .icon { color: #ff4d4f; }
.text-center {
  text-align: center;
  margin-top: 30px;
}
.next-btn {
  padding: 8px 24px;
  font-size: 14px;
}
.publish-form { margin-top: 20px; }
.publish-form .el-form-item { margin-bottom: 25px; }
.button-group {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 30px;
}
.empty-state {
  color: #909399;
  padding: 50px 0;
  text-align: center;
}
.upload-demo { margin-bottom: 15px; }
</style>